package src.com.qf.service.impl;

import src.com.qf.dao.UserDao;
import src.com.qf.dao.impl.UserDaoImpl;
import src.com.qf.entity.User;
import src.com.qf.service.UserService;
import src.com.qf.utils.EmailUtils;
import src.com.qf.utils.JdbcUtil;
import src.com.qf.utils.MD5Util;

public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();
    @Override
    public int checkUserName(String username) {
        int result = 0;
        try {
            JdbcUtil.begin();
            User user = userDao.selectUserByUsername(username);
            if (user!=null){
                result=1;
            }
            JdbcUtil.commit();
        } catch (Exception e) {
            JdbcUtil.rollback();
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public int register(User user) {
        int result = 0;
        try {
            JdbcUtil.begin();
            //盐值加密和迭代
            String str = user.getPassword() + user.getUsername();
            for (int i =0; i< 1000; i++){
                str = MD5Util.getMD5(str);
            }
            //经过千次盐值加密后的密文进行存储
            user.setPassword(str);
            result = userDao.insertUserByUser(user);

            if (result == 1){
                //发邮件到所填邮箱
                EmailUtils.sendEmail(user);
            }

            JdbcUtil.commit();
        } catch (Exception e) {
            JdbcUtil.rollback();
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public int active(String activeCode) {
        int a = 0;
        try {
            JdbcUtil.begin();
            a=userDao.updateStatusByActiveCode(activeCode);
            JdbcUtil.commit();
        } catch (Exception e) {
            JdbcUtil.rollback();
            e.printStackTrace();
        }
        return a;
    }

    @Override
    public User login(String username, String password) {
        User user = null;

        try {
            JdbcUtil.begin();
            user = userDao.selectUserByUsername(username);
            JdbcUtil.commit();
        } catch (Exception e) {
            JdbcUtil.rollback();
            e.printStackTrace();
        }
        String str = password+username;
        for (int i =0; i <1000; i++){
            str = MD5Util.getMD5(str);
        }

        if (user.getPassword().equals(str)){
            return user;
        }
        return null;
    }
}
